package bookManage.Controller.servlet;

import bookManage.Model.service.ServiceImpl;
import bookManage.utils.DBUtil;
import bookManage.utils.JsonUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * @BelongsProject: library-management-system-master
 * @BelongsPackage: bookManage.Controller
 * @Author: yuan wang
 * @CreateTime: 2023-02-02  11:00
 * @Description: 删除书籍的Servlet，适用于管理员在点击书详细信息后调用这个方法，
 * @Version: 1.0
 */
@WebServlet(name = "DeleteBook", value = "/manager/BookShow/BookContent/DeleteBook")
public class DeleteBook extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String jsonString = String.valueOf(JsonUtil.getJson(req));
        JSONObject jsonObject = JSON.parseObject(jsonString);

        Integer id = jsonObject.getInteger("id");

        ServiceImpl service = new ServiceImpl();

        PrintWriter out = resp.getWriter();
        JSONObject object = new JSONObject();

        try {
            if (service.delBook(id) == 0) {
                object.put("code", "-1");
                //这里可以提前在前端的时候去掉不在馆书籍的删除按钮，也可以都加上，如果加上则显示下面这个提示信息
                object.put("message", "删除书籍失败，可能原因：无法删除不在馆的书籍。如不是这个原因还请管理员自行判断");
                out.println(object);
            } else {
                object.put("code", "200");
                object.put("message", "删除书籍成功");
                out.println(object);
                //这里可以做一个页面跳转，跳转回到管理员的书籍详细页面，类似于刷新界面的功能
                //同样，页面跳转可以由前端实现，后端实现也可以，这里不再赘述
            }
        } catch (SQLException e) {
            object.put("code", "-1");
            object.put("message", "删除书籍失败");
            out.println(object);
        } finally {
            try {
                DBUtil.freeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doGet(req, resp);
    }
}
